Skip to content

fix(recompiler): run vertex programs as one-lane waves without vertex subgroups - #4470

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
overlordxrz-source:fix/vertex-one-lane-waves
Oct 12, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
overlordxrz-source:fix/vertex-one-lane-waves

Conversation

@overlordxrz-source

Copy link
Copy Markdown
Contributor

What

On lavapipe and MoltenVK every vertex program that declares a subgroup capability is refused by the driver's shader validation (ShaderValidation.cpp:205):

AGC graphics: subgroup capability 61 is unsupported for shader stage 1

Capability 61 is GroupNonUniform and stage 1 is VK_SHADER_STAGE_VERTEX_BIT. Most vertex programs declare it, because the entry EXEC is a ballot. Neither driver lists the vertex stage in subgroupSupportedStages:

The validation is right to refuse these modules, so this PR changes what the recompiler emits for vertex programs on such devices.

How.

  • SpirvTarget::vertexSubgroups (default true) records whether the device's subgroupSupportedStages has VK_SHADER_STAGE_VERTEX_BIT. VulkanDevice::buildTarget sets it. It is part of the cache key and of the serialized request (version 17 → 18; older requests read as true).
  • When it is false, HostSubgroupSize gives vertex and local programs a host subgroup of 1 lane. The existing narrow-host machinery takes it from there, so each invocation runs as a wave of one lane:
  • The GroupNonUniform* instructions now go through four helpers in SpirvSubgroup.cpp (EmitSubgroupBallot, EmitSubgroupBallotFindLsb, EmitSubgroupShuffle, EmitSubgroupElect), which emit the subgroup instruction as before or the one-lane form. The call sites keep their ID allocation order.
  • Pixel, compute, mesh and tessellation programs are unchanged, and so is every program on a device whose vertex stage has subgroups.

Why results are right for the lanes that exist. Each lowering is what the subgroup instruction returns in a subgroup of exactly one invocation. A wave with one vertex is also a wave the console launches, and s3 now says so. EXEC starts as ballot(true) = lane 0, so v_mbcnt, s_ff1/v_readlane waterfalls, v_readfirstlane, saveexec and branches compute what they compute for lane 0 of such a wave. Cross-lane reads keep the rules narrow hosts already have (TechnicalDebt, "lanes outside the host subgroup"):

  • a constant v_readlane_b32 of lane ≥ 1 and v_permlanex16_b32 throw (... is outside the 1-lane host subgroup ...), as they do on 8-lane hosts today;
  • v_permlane16_b32 without fetch-inactive, ds_swizzle, ds_bpermute and DPP take any other lane as inactive (old value or 0).

Limits.

Related: #3891 (draft, Apple ARM64 AOT) folds away a constant LaneId < 32 mask so its cube shader avoids the vertex capability on MoltenVK. That removes the capability for one shape only; this PR covers any vertex program.

Tested

Rig evidence (before this change): our Linux sweep on main b42ef24 with Mesa lavapipe stops eight homebrew titles at the error above: Stremio Plus, ProsperoStore, EVO Player, OpenNOW, PS5VR, Jelly5, Emby5 and Nuvio PS5. They have not been rerun with this change, so whether they get further, and where they stop next, is unknown until a rig rerun.

This change, on main 3d8ffeb, in an aarch64 Linux sandbox with zig 0.17 (clang) and no GPU:

  • agc_shader_memory, new verifySingleLaneVertexWave:
    • with vertexSubgroups = false, a lane-op program (v_mbcnt_lo/hi, v_readfirstlane_b32, v_readlane_b32 lane 0) and an s_ff1_i32_b64 waterfall build with no GroupNonUniform* capability, instruction or subgroup built-in; with true both use them;
    • s3 is 0x101 without vertex subgroups (the same module for device subgroup sizes 4 and 32), and 0x4040 with them on 64 lanes;
    • a constant read of lane 31 throws outside the 1-lane host subgroup, and builds on a 32-lane vertex subgroup;
    • a pixel program keeps its subgroup operations when only the vertex stage lacks them;
    • the flag survives serialization, the replayed request builds the same module, and the flag changes the cache key.
    • The serialization test now expects version 18 and rejects 19.
  • The recompiler library and ShaderMemory.cpp built natively. 35 of the 36 agc_shader_memory functions pass, including verifyLanesOutsideHostSubgroup, verifyHalfWaveReduction, verifyNarrowVertexWave and the new one. verifyGuardedNullPointers can't run in that harness: it reads guest memory through a stubbed GuestMemory.
  • 8 programs (the above, lane 31/63 reads, v_permlane16_b32, v_permlanex16_b32, the NVIDIA: wave64 NGG culling vertex program reads lane 63 of a full-wave OR reduction (Taxi Chaos 2, PPSA30279) #2783 culling scan) as vertex and pixel programs × wave32/64 × subgroup sizes 4/8/32/64, 128 compilations with vertex subgroups on (the default): all 96 modules that build are byte-identical to main's. The 32 that throw give the same messages; only the request version embedded in the message changes.
  • The same 64 vertex compilations without vertex subgroups: all 36 modules that build pass spirv-val --target-env vulkan1.1 (SPIRV-Tools 2026.4) and use no subgroup capability. The 28 that throw are the constant lane ≥ 1 and v_permlanex16_b32 reads above. The pixel modules are byte-identical to main's.
  • x86_64-windows-gnu -fsyntax-only of every changed .cpp (including VulkanDevice.cpp and ShaderMemory.cpp): no errors, no warnings on changed lines.
  • tools/check_conventions.py --base origin/main passes.

Not tested: a Windows build or run, any run on lavapipe, MoltenVK or another GPU, and any title.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Unblocks: all eight titles move past it on the rig (lavapipe, 120 s): Stremio Plus and ProsperoStore reach last provoking vertex with explicit per-vertex flat interpolation is unsupported; EVO Player, OpenNOW, PS5VR, Jelly5 and Emby5 run past the 120 s timeout with no stop; Nuvio PS5 throws std::logic_error from a later stage
  • AI-assisted: yes

… subgroups

lavapipe and MoltenVK leave the vertex stage out of subgroupSupportedStages,
so the driver's shader validation refuses every vertex program that declares
GroupNonUniform ("subgroup capability 61 is unsupported for shader stage 1").
Most do, since the entry EXEC is a ballot.

The device target now records whether the vertex stage has subgroups. When
it does not, vertex and local programs get a host subgroup width of 1: s3
reports one vertex and one primitive, the lane id is 0, a ballot is the
invocation's own bit, a shuffle returns the invocation's value, an elect is
true and a half-wave reduction read is the key itself. Reads of other lanes
keep the existing narrow-host rules and throw where they did. Devices with
vertex subgroups emit the same SPIR-V as before.

@Dextroid17 Dextroid17 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PPSA28997 gets past this wall on lavapipe with this PR's libs. The case this body describes — a device whose vertex stage has no subgroups — is the one here: Selected GPU name=llvmpipe (LLVM 23.1.1, 256 bits) vendor=0x10005 device=0x0 subgroup=8, on which the run used to abort with exactly that error.

Same relinked app.elf and the same staged tree for both runs; only libs/ was replaced. Logs: ~/rea-work/gow-run4.log (before) and ~/rea-work/gow-run5.log (after), launched the same way:

systemd-run --user --scope -p MemoryMax=22G -p MemorySwapMax=8G -- \
  env VK_ICD_FILENAMES=…/lavapipe/lvp_icd_abs.json DISPLAY=:0 timeout 600 ./app.elf

Before — libs from a main-era build (33ae282e4), gow-run4.log:152-158:

[videoout] presentation failed: AGC graphics: subgroup capability 61 is unsupported for shader stage 1
terminate called after throwing an instance of 'std::runtime_error'
  what():  AGC graphics: subgroup capability 61 is unsupported for shader stage 1
run4 exit=134

That is 12 s of run (09:55:03 → 09:55:15), 10 StorageTexture lines and one rect-list draw, dead at the first presentation — before the shader cache flushed any totals, which is why there is none to compare below.

After — this PR rebased onto 57dc13602 (applied without conflicts, 048b59c3a) and built, gow-run5.log:

run5 (PR #4470 libs) start 2026-10-12T10:05:33-04:00
[shader-disk-cache] (10 s): 0 hits, 4 misses, 5 writes (0.2 MiB), 0 load failures, 0 write failures; 0.0 MiB read in 0.7 ms (totals: 0 hits, 90 misses, 90 writes)
[PS5VideoMedia] INFO: AvPlayerResource FreeDirectMemory 3342336
[src/PadInput.cpp:54 openController] Pad: connected game controller: PS4 Controller (type 4, sensors accel=1 gyro=1, touchpads=1, led=1, trigger rumble=0)
run5 exit=124
  • The subgroup capability error and any [videoout] presentation failed line are absent from the after log altogether (0 occurrences each, against 2 and 1 before).
  • The run went further: 44 StorageTexture lines — 11×1920x1080, 10×2048x1088, 10×1024x544, 8×128x1 and smaller, vk formats 37×11, 9×10, 16×10, 76×8, 122×4, 100×1 — one rect-list draw, ten AvPlayerResource FreeDirectMemory INFO lines, a pad connect.
  • It was still running when the 600 s wrapper killed it (run5 exit=124, 10:05:33 → 10:15:43); the timeout path dumps core, so that is a kill rather than a clean exit.
  • The cache key moved with the change: the after log's directory is …/shader_cache/7ec63b111d1bd1ac (source version 7ec63b111d1bd1ac, format 27) where the before run's was 2169f238263a0f90 — those are ShaderCacheVersion source versions, not commits — and the totals are (totals: 0 hits, 90 misses, 90 writes) with 0 load and 0 write failures in that interval. A new key selects a new empty directory; the old one is still on disk with its 86 files. CacheKey.hpp is in this diff, so the move is expected.

Attribution. git log 0ef9dc928..57dc13602 -- core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp core/shader/recompiler core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp is empty (19 commits in that span), so for these paths the two builds differ only by this PR. The two builds do also differ by main's nine other commits in between, which I did not control — so this shows the change is enough to get past the wall here, not that nothing else contributed.

The SHAs, for whoever re-checks: before-sha 33ae282e4; PR head 0bcff53b2 (parent 0ef9dc928); the rebase tested, 048b59c3a (parent 57dc13602, current main). The before libs are no longer in the staged tree — it was rebuilt at 10:02, so only gow-run4.log carries that state.

Caveats. Not gameplay: after the pad line the log has three teardown lines and then the kill, so this is "past the wall, title alive". AvPlayer shows only that repeated free-memory INFO line, so "the intro video is playing" would be an inference the log does not support. All of it is lavapipe — no real-GPU comparison. And this title needed its own PSN plugin parked (run-gow/.disabled/PSN.prx.guest.prx) before it reached presentation at all; that is a separate crash in that plugin's initialiser, unrelated to this change.

Posting as an observation only — nothing requested, and I have no PR against this path.

Written with AI assistance.

Hermes Agent 🤖 at your service

@Xabilimon1

Copy link
Copy Markdown
Contributor

Tested this PR on MoltenVK, since the description lists that as not tested.

Setup: Apple M3, macOS 27.0.1 (26A434), x86-64 under Rosetta, Vulkan SDK 1.4.363.0 with MoltenVK 1.4.2. vulkaninfo reports subgroupSize = 32 and subgroupSupportedStages = TESSELLATION_CONTROL | FRAGMENT | COMPUTE.

Base: mugurc:macos-port (de3ef5d53) merged with main 0ef9dc928 (this PR's base), then this PR (0bcff53b2) on top. Two things in that base are mine and not in either branch:

  • three local build fixes, because code main added since the last re-stack does not compile on macOS: O_DIRECT in DescriptorControl.cpp, the physical-span blocks in DirectMemory.cpp (__linux__ only, while WatchMapping also builds on __APPLE__), and missing <initializer_list> / <sys/mman.h> includes in GuestGetrlimit.cpp and GuestKernelStackProtect.cpp;
  • this PR conflicts with macos-port in five recompiler files: its commit 47bf3675a already routes shuffles and ballots through EmitLaneShuffle / EmitLaneBallot (results stored via EmitConvergentResult). I kept those helpers and made them emit through EmitSubgroupShuffle / EmitSubgroupBallot. @mugurc, this will need the same merge when macos-port is re-stacked.

Results (ctest -j1 --timeout 30, without lds_atomics64, flip and video_out, 920 tests, same set of skips in both runs):

failed
without this PR 23
with this PR 21
  • agc_driver_ngg_vertex_wave_info fails without the PR (subgroup capability 61 is unsupported for shader stage 1) and passes with it (3 of 3 runs alone).
  • patched_libraries timed out at 30 s in the run without the PR and passed in 3 s in the run with it. @DavidSamir reported it timing out under load on macOS support #1, so I don't count it as an effect of this PR.
  • No test that passed without the PR fails with it.

With the vertex-subgroup skips removed locally from the tests (not part of this PR):

  • agc_driver_exec_host_lanes: the vertex draw passes, 3 of 3.
  • agc_driver_ngg_vertex_wave_reduction: v_permlanex16_b32 from lanes 16-31 is outside the 1-lane host subgroup that runs this wave64 program at one lane per invocation, 3 of 3. That is the limit described in the PR, so its skip should stay.

Not tested: any title, lavapipe, Windows.

AI-assisted: yes (Claude Code).

@oneandonlydean oneandonlydean self-assigned this Oct 12, 2026
@Amoenus

Amoenus commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Serialization coordination completed: #4470 is merged. #4451 is now rebased on main 2f4cc8983 at 3040cd741. It writes version 19 and preserves original #4470 version 18 requests for subgroup support both off/on. Original-serializer fixtures and the malformed-reader fault control pass; full NVIDIA suite: 990 passed, 0 failed, 7 skipped.

Correction to the earlier GPU matrix: setting APS5_NO_GPL=0 disables GPL too. Actual GPL-on testing leaves it unset. The corrected matrix has remaining AMD runtime failures, so the earlier all-green GPL claim is withdrawn. These failures, controls and fresh-build retesting are maintained in #4451; serializer compatibility itself is separately validated.

The proposed #4470-first sequence is complete. #423/#4031 still independently allocate different version 18 layouts and need adaptation to the canonical merged format; this is a source audit, not combined-head validation.

@Dextroid17

Copy link
Copy Markdown
Contributor

Confirmed from both heads, and the silent half is real. Read at this PR's 0bcff53b2 and at #4451's 4edc8d326:

Both also write 18u and raise the ceiling to 18u. The two new reads sit in different functions — the target section and readPixelInfo — so the serializer merges with no textual conflict at all, and the only thing that conflicts is the tests' prefix assertion (NVNQQREAAAA= → NVNQQRIAAAA=). That is the part that matters: a version-18 blob written by either head is not the layout the other expects, and after a merged landing both readers accept 18. A clean "no conflicts" report will not show it, which is why the version number itself has to carry the decision.

I have no stake in which lands first, but the rule the evidence supports is one version per layout change: whichever is second takes 19, and both bodies should state the order so the second is not merged on a mergeability report. Your sequencing — this PR first, the alpha fields rebased to 19 with a v18 fixture retained — does that, and retaining the fixture is the part that keeps the v18 blob readable afterwards.

Written with AI assistance.

@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
#4031 core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp L1640, L1645
#4048 core/shader/recompiler/CacheKey.hpp L245
core/shader/recompiler/Recompiler.hpp L234
#4566 core/shader/recompiler/SpirvBackend/src/SpirvAlu/SpirvAluEmitterMath.cpp L190-193
core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp L119-121, L159-164
core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp L134-136
core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp L1183-1185
core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvSubgroup.cpp L186-188
#4599 core/shader/recompiler/SpirvBackend/src/SpirvAlu/SpirvAluEmitterMath.cpp L190-193
core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp L119-121, L159-164
core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp L134-136
core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp L1183-1185
core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvSubgroup.cpp L186-188
#4650 core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp L739, L760, L769, L791
core/shader/recompiler/Recompiler.hpp L234

@kr4y4

kr4y4 commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

A run on two real GPUs, since the description's run had none.

Setup: Windows 11 (26200), WinLibs GCC 15.2.0 r7, Release, CI configure flags, an RTX 4070 Laptop GPU and an Intel Raptor Lake-S iGPU. The head 0bcff53 merged into main 2a5eca1.

As built: both GPUs have subgroup arithmetic in vertex shaders (agc_driver_ngg_vertex_wave_reduction runs instead of skipping), so the one-lane path isn't taken.

  • agc_shader_memory (with verifySingleLaneVertexWave), agc_driver_graphics, agc_driver_vertex_fetch, the flat_apertures parts and the wave64 tests pass on both GPUs with --repeat until-fail:3.
  • Full suite (ctest --timeout 120 --parallel 4): 973 of 973 on the RTX 4070. On the iGPU 972 of 973; the one failure, agc_driver_f32_dot2_rounding, fails the same way on main (no shaderFloat64, test(agc): skip the f32 dot2 rounding test on devices without shaderFloat64 #4528).

With the one-lane path forced: to run it on real hardware, I set target.vertexSubgroups = false in VulkanDevice::buildTarget locally (not a proposal) and reran the full suite on both GPUs.

  • Every test passes except agc_driver_ngg_vertex_wave_reduction (and, on the iGPU, the dot2 test above). That covers all the draw tests, with vertex and local programs running as one-lane waves.
  • agc_driver_ngg_vertex_wave_reduction is refused at recompile: v_permlanex16_b32 from lanes 16-31 is outside the 1-lane host subgroup that runs this wave64 program at one lane per invocation. That test skips on a device without vertex subgroups, so it only ran because of the forced flag, and the program is refused, not computed wrong.

Written with AI assistance.

@Dextroid17

Copy link
Copy Markdown
Contributor

Two details in your run worth pinning to the head you built.

1. The one-lane lowering is exercised without your local flag. The tests added here take vertexSubgroups as an argument instead of reading it from the device (core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp:1480 on 0bcff53b2), and verifySingleLaneVertexWave() is called unconditionally from the test's mode list (ShaderMemory.cpp:3198), so the recompiler builds the one-lane form wherever that test binary runs, whatever the host device is. What your local buildTarget change was needed for is the driver route, where the value comes from the device — and that route is the case my earlier run covers: Selected GPU name=llvmpipe (LLVM 23.1.1, 256 bits) … subgroup=8 has no subgroup arithmetic in the vertex stage, so the flag is computed false by itself and PPSA28997 gets past the presentation abort. Your two GPUs and that title run bracket the same path from both ends: with vertex subgroups nothing moves (your 973/973), without them the one-lane form is what carries a title.

2. The refusal you forced is not reachable from a device. The flag is computed as target.vertexSubgroups = (state->subgroup.supportedStages & VK_SHADER_STAGE_VERTEX_BIT) != 0 (core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp:2968 on this head), and NggVertexWaveReduction.cpp:135-137 skips on exactly that predicate — skipped, the device has no subgroup arithmetic in vertex shaders. A device can only produce the false flag where that test does not run, so the refusal you saw under the forced flag guards a configuration no device reaches, and it is still a refusal rather than a wrong result. Reporting it as a guard rather than as a wall is the accurate reading, and holding the hack back from the PR is the right call: the driver-level behaviour of a subgroup-less device is what the title run stands on, and it is not reproducible on either of your GPUs.

Written with AI assistance.

@oneandonlydean
oneandonlydean merged commit 0c75934 into boykopovar:main Oct 12, 2026
9 checks passed
RINNECODER added a commit to RINNECODER/AnyPS5 that referenced this pull request Oct 13, 2026
* fix(recompiler): read P10 of a flat input as the provoking vertex

A FLAT_SHADE input without pass-through that a pixel shader reads
through v_interp_mov_f32 P10 became an explicit per-vertex input and
read vertex 1 minus vertex 0. With the last provoking vertex the
pipeline then threw ("last provoking vertex with explicit per-vertex
flat interpolation is unsupported"), which stopped all three
ps5-opengl titles in the catalog.

ps5-opengl reads every flat input through P10 when GL's last-vertex
convention is in effect, and its driver passes the GL 4.6 CTS on a PS5
(boykopovar#1413). Such a read now returns the provoking vertex's value, as P0
does, and only a P20 read keeps a flat input per vertex. The lane was
not measured on the console itself, so FragmentParameter records it
and a pipeline using the first provoking vertex throws.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 99edf94)

* fix(shader): keep f32 denormals in compares when denormals are kept

With the f32 denormal field of FLOAT_MODE set to keep, v_cmp_X_f32 and
v_cmpx_X_f32 read a denormal operand as zero: NVIDIA, RADV and lavapipe
all flush denormals in their float compares. Compare the operands as
sign-magnitude integers instead, with NaN handled apart. Compares with
flushed denormals are unchanged. This matches RDNA2 (gfx1036) on 256
operand pairs per opcode, with f32 denormals kept and flushed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit de54527)

* fix(shader): prove masked writes through guarded first-lane reads

(cherry picked from commit fded8a7)

* fix(shader): match half-wave reductions over relatively addressed vector registers

A program that uses v_movrels_b32 or v_movreld_b32 keeps every vector
register from the lowest relatively addressed one up in a per-invocation
window array, so its plain register accesses become LoadVectorWindow and
StoreVectorWindow. The half-wave reduction matcher followed only SSA values,
so a wave64 scan, v_permlanex16_b32 join and lane 31/63 read through that
array threw that lane 63 is outside the 32-lane host subgroup.

The matcher now reads a window load at a constant slot as the value of the
last store to that slot earlier in its block, unless a store at a runtime
slot lies in between; each invocation owns its array, so that is the value
the load returns. A store in another block, or a v_movreld_b32 at a runtime
M0 in between, still throws. This was the only refused lane 32-63 read left
among Ghost of Yotei's wave64 graphics programs (one pixel program).

(cherry picked from commit 364d7cf)

* fix(shader): apply VOP3P neg_lo/neg_hi to packed 16-bit integer sources

The packed integer ops (v_pk_add/sub/mul_lo/mad/min/max/shift) read their
16-bit sources without the VOP3P negate bits. Hardware negates a 16-bit
source by flipping bit 15 for integer ops too, and Sony's compiler relies
on it: UE5's TSR history update clamps its -1 neighbour offsets with
v_pk_max_i16 v14, neg(lit 0x7fff), v14, i.e. max(-1, minY - y). Without
the modifier that became max(0x7fff, x), the x-1/y-1 taps of the 3x3
input filter read out of bounds as zero, and the history lost ~16 % of
its energy every frame (Sword of the Sea's missing glow).

The new execution test covers every packed integer op with neg_lo and
neg_hi, op_sel interplay, clamp and the TSR literal case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013fa2MbmdFLVr8YHuVjucHE
(cherry picked from commit 48654bd)

* fix(recompiler): give an early-return selection a merge when its parent's other arm reaches the same join

A selection outside loops whose one arm only returns and whose other arm
branches to a join it does not dominate gets an empty block on that edge
as its merge (splitOneReturnJoin), but only when every other predecessor
of the join dominates the selection or is dominated by it. When the
parent selection's other arm is a region that ends in the same join, the
selection has no structured merge and the shader fails to recompile.

When every structurization attempt fails, Structurize now runs them again
and accepts that split for any join the selection does not dominate. The
split only inserts an empty block on the edge from the selection to the
join. Graphs that structurize on main keep their result.

A synthetic CFG and a synthetic program cover the shape; both fail on main
with "conditional block N has no structured merge".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Fnrk5Dazjb2tLooVSpdRQq
(cherry picked from commit 7f5cd44)

* fix(shader): prove masked lanes unread for every select in one backward pass

MaskedSelectEliminator walked forward from each select to see whether the
lanes its mask excludes are read. Since fda4aa9 the walks pass explicit-LOD
gathers, size queries and guarded image writes, so in a large pixel shader
most of them cover the rest of the program, and the cost grows with the
square of its size (boykopovar#3504).

The pass now computes, for every value, the set of masks under which it is
unread, from its uses backwards: a use guarded by a condition contributes the
masks that condition implies, a lane-local use adds what its result is unread
under, and any other use contributes nothing. A select is dropped when its
mask is in its own set. Loops are solved as strongly connected components.
The rules for guards, lane-local uses, loops, whole quad masks, selected
execs, rebuilt mask words and guarded first-lane reads are the ones the walk
applied. A first-lane read passes the masks its read mask implies when its
own result is unread outside that read mask, which is solved once per read in
the same way. The walk's step limit, its 64-level implication depth and its
first-lane nesting depth are gone, so a proof no longer depends on the order
of the questions.

(cherry picked from commit d37463e)

* fix(shader): decorate rect-list gl_Position as Invariant

The vertex stage already marks Position Invariant, and the rect-list stages have to match that interface.

(cherry picked from commit 436e419)

* fix(shader): preserve ancillary proofs across relative VGPR accesses

(cherry picked from commit b3587f9)

* fix(shader): restrict ancillary refolding to live builtin uses

(cherry picked from commit ae049e7)

* refactor(shader): drop unused folded constants and unreachable blocks after specialization

SpecializeSpirv hoists every instruction it folds into a module-level
constant and keeps that constant after its last use has folded away
too. It also leaves each block that a folded branch cuts off as
OpLabel; OpUnreachable. A formatted buffer helper's 77-case format
switch leaves about 1,800 such blocks.

Emit only the folded constants that something still refers to, and
remove OpLabel; OpUnreachable blocks that no instruction names. Merge
and continue targets of live constructs are named, so they stay.

The specialized modules lose words, not behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 3ea8967)

* fix(recompiler): run vertex programs as one-lane waves without vertex subgroups

lavapipe and MoltenVK leave the vertex stage out of subgroupSupportedStages,
so the driver's shader validation refuses every vertex program that declares
GroupNonUniform ("subgroup capability 61 is unsupported for shader stage 1").
Most do, since the entry EXEC is a ballot.

The device target now records whether the vertex stage has subgroups. When
it does not, vertex and local programs get a host subgroup width of 1: s3
reports one vertex and one primitive, the lane id is 0, a ballot is the
invocation's own bit, a shuffle returns the invocation's value, an elect is
true and a half-wave reduction read is the key itself. Reads of other lanes
keep the existing narrow-host rules and throw where they did. Devices with
vertex subgroups emit the same SPIR-V as before.

(cherry picked from commit 0bcff53)

* fix(shader): store unaligned 32-bit BDA writes byte by byte

EmitBdaWrite, used for buffer stores through GPU-selected descriptors, recorded an
Unaligned fault and dropped every 32-bit store whose address is not 4-byte aligned.
EmitBdaStore and the BDA reads already take the byte path for unaligned addresses, and
raw buffer accesses use the exact bytes, as RDNA does in unaligned mode. The unaligned
case now stores the four bytes one by one like the 8- and 16-bit stores of the same
function.

Sword of the Sea hit this about once per frame from one compute store, so four bytes
were lost and a fault was reported each time.

The BDA store execution table now also runs through EmitBdaWrite; its unaligned dword
cases failed before this change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 803a131)

* fix(shader): count only id operands as uses when dropping specialization debris

referencedIds() took every operand word of every instruction as a
possible id, so a literal that happened to equal the id of a dead folded
constant or an unreachable block kept it: the OpTypeInt width 32 kept a
dead constant %32, LocalSize literals kept dead labels.

Visit only the <id> operands of each instruction. Literal operands are
skipped for the instructions that carry them: type widths, counts and
image parameters, constant values, storage classes, memory access and
image operand masks (their trailing ids still count), composite and
shuffle indices, OpArrayLength members, extended instruction numbers,
entry point names, execution modes, merge and function controls, branch
weights, OpSwitch case values (two words for a 64-bit selector) and
group operations. An instruction without a listed layout still counts
every word, so an unknown instruction can only keep debris, never drop
something in use.

The SpirvModule case now also folds a switch whose dead constant has id
32 and whose dead blocks' ids appear as LocalSize literals; it fails
without this change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 676622f)

* fix(shader): return 0 for 8-bit UNORM color comparison

image_sample_c on an 8-bit UNORM T# returns 0 for every compare
function on gfx1035, as on 8-bit sRGB (measured on the hardware oracle
in the review of boykopovar#3438), but the emulated comparison still compared the
red channel. 8, 8_8 and 8_8_8_8 UNORM now return 0 like 8-bit sRGB.

Every texel comparison of those formats is 0, so a bilinear cube
without DISABLE_CUBE_WRAP and an anisotropic S# cannot change the
result; both are accepted for them, as the cube already was for 8-bit
sRGB. Other formats keep both refusals.

The test rows that check real comparisons move to 16_16 UNORM.

(cherry picked from commit a9c625a)

* fix(recompiler): leave out descriptor sources behind a branch the capture decides

A compute kernel that picks a buffer or an image path from an SRT word reads
the same address as a V# in one path and as a T# in another. The resource
tracker now records which block uses each descriptor source and builds the
resource control flow from the structured block terminators, so a source whose
only uses sit behind a conditional branch with a clean, evaluable condition is
left inactive (bound as zero words, not validated) when the capture takes the
other path. A condition that reads inaccessible memory is not evaluable instead
of throwing.

PPSA15246 (Teardown) stopped on "runtime image descriptor is invalid" for the
untaken path of such a kernel.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 7b9c7ca)

* style(recompiler): drop the comment above the resource control flow planner

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 0accdb4)

* fix(recompiler): track which branch uses each image, not only each descriptor source

Several image instructions of different dimensions on the same T# address share
one descriptor source, so a source stays active as soon as one of them is taken
and the others are still checked against the T#. Record the images a block uses
as well, deactivate the images used only behind a branch the capture does not
take, and bind them as null descriptors.

PPSA15246 (Teardown) then passes the "incompatible with the static runtime
image interface" check of the three image_store variants that are not taken.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 37003b7)

* fix(recompiler): evaluate pruning conditions without throwing on null roots

A branch condition that reads through a null user-data pointer is now
treated as not evaluable instead of being caught, so every successor
stays active.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 7d508cf)

* feat(shader): give reads the masked-select pass keeps the whole pixel ancillary word

A packed ancillary word that still reaches an export, or any other read
the masked-select pass cannot drop, no longer stops the recompile. After
that pass every remaining use gets the composed word: the primitive class
at bits 0-1, SampleId at bits 8-11 and Layer at bits 16-28, with every
other bit zero. Those lanes do export the ancillary VGPR on the console,
so the word has to be right, not just present.

The primitive class (0 point, 1 line, 2 triangle, 3 rectangle) comes from
the draw. RasterPrimitiveOf maps rect lists to 3, line lists on the vertex
path to 1 and everything else the driver accepts to 2, because its
geometry and tessellation paths only output triangles. It reaches the
shader as pipeline specialization constant 8233, the way dual-source
blending does: a request field that is folded into the specialized
module and is part of the result memo, the draw key and the serialized
request (version 17).

Only shaders that read the class pay for it. ShaderInfo records the read
(disk cache format 28), and only those shaders put the class in their
module key, so a shader that reads just the sample or layer field keeps
one module for every primitive class. The draw sets the class only when
the pixel shader loads the ancillary VGPR, so other draws keep the draw
cache entries they have today.

The VRS rates (bits 2-5) and the eye id (bit 7) are 0 because the driver
supports neither VRS nor multiview. SampleId is 0 because the driver
rejects MSAA and per-sample shading, and Layer is 0 while it ignores
vertex layer exports. TechnicalDebt.md records the layout sources and
these assumptions.

Tests:
- pixel_ancillary builds an export to target 0 whose two channels select
  between a packed value and a phi carrying the word. It checks the word
  for each primitive class, sample and layer, checks that the three
  shapes the masked-select pass keeps now compile with the composed word,
  and that a program whose select the pass drops reads no class.
- agc_driver_pixel_ancillary_word exports the word from a draw and reads
  back 2, 3 and 1 for triangle, rectangle and line. A shader that reads
  only the sample field shares one module across the classes, and the
  whole-word shader gets one per class. It also checks RasterPrimitiveOf.
- agc_shader_memory covers the version 17 round trip, and
  agc_shader_disk_cache the new flag.

Both ancillary tests fail with the old refusal when the composition is
disabled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 18d9874)

* fix(shader): move the primitive class to request version 19 and compose the ancillary word with render target index 0

main reads target.vertexSubgroups at request version 18 since boykopovar#4470, so
reading the pixel primitive class at 18 as well read a version 18
request written by main one byte short. The class is now written and
read at version 19. agc_shader_memory loads a version 18 request as
main writes it, and it fails with "truncated data" when the class is
read at 18.

The composed word no longer reads the Layer builtin for bits 16-28.
Draws render to a single layer and guest layer exports are ignored, so
no stage writes Layer, and AMD's Windows driver drops the writes of a
fragment shader that reads it unwritten (boykopovar#4800). The field is the
constant 0 and pixel_ancillary checks that the composed program has no
Layer read. The debt entry names the bits that have no source and are
assumed zero (2-7, 12-15, 29-31), and says that a change which makes
draws export a layer must restore the read.

(cherry picked from commit c52321f)

* fix(shader): read the ancillary render target index as 0

No pre-rasterization stage writes Layer: vertex layer exports are
ignored, so the first layer is used and the render target index field
of the packed ancillary word is 0. The lowering read the Layer builtin
for it instead. AMD's Windows driver drops the color writes of a
fragment shader that consumes an unwritten Layer, which made
agc_driver_relative_ancillary fail on AMD hardware (boykopovar#4800); lavapipe
returns 0 there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 3334e41)

* fix(shader): keep direct VGPR accesses in SSA when the window has only relative reads

A program that uses relative VGPR addressing placed every register from the
lowest relatively addressed one upward in the window array, so even direct
accesses became array loads and stores. A descriptor spilled with v_writelane
and restored with v_readlane then lost its definition, and resource analysis
refused GetSamplerResource with ReadLane(LoadVectorWindow(Immediate)) (GTA V,
PPSA04264, shader 0x25a889400).

When the program has no indexed writes (v_movreld, v_movrelsd, v_swaprel),
direct accesses stay SSA registers and each direct write is mirrored into the
window for the relative reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1W4jdNSKTV7xwuS6xQPJV
(cherry picked from commit 2ecbbe4)

* test(agc): give the formatted buffer vertex case clip distances and the zero-position pixel shader its push slot

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit b1ee794)

* test(agc): compare the cost of more formatted loads with the first one, not with the module

agc_formatted_buffer_once required two more formatted loads from a known
descriptor to add less than a tenth of the module. The module was mostly
what specialization left of the folded format switch. Without those
leftovers it has 1,219 words and the two call sites add 225, so the
ratio failed while nothing was duplicated.

Require the two extra loads to add fewer words than the first one,
which also brings the shared function. A second copy of that function
per load still fails this check, as well as the function count checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit bb13259)

* Metal draw path: pass the raster primitive class for kept pixel ancillary words

Upstream 18d9874 sets ShaderPixelStageInfo::rasterPrimitive in the Vulkan
driver's DrawDecode; the Metal/Rosetta path decodes draws in DrawDispatch, so
set it there too. Without it every primitive read as a triangle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(agc): a relative read of the whole ancillary word gets the composed word

The relative-ancillary test expected the whole-word read through
v_movrels to be refused, which was main's behaviour before the word was
composed. It now converts that read to float and exports it: the
composed word of a triangle draw is 2 (primitive class 2, sample 0,
layer 0), so the pixel is 255, with and without the implicit position
inputs in front of the ancillary VGPR. TechnicalDebt's relative
addressing entry no longer says that whole-word uses throw.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit d0aca69)

---------

Co-authored-by: AlxcBTW <187763517+AlxcBTW@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alex <270190108+CouchRiv@users.noreply.github.com>
Co-authored-by: eljackjoestar-cmd <eljackjoestar@gmail.com>
Co-authored-by: Celegans12 <53881228+Celegans12@users.noreply.github.com>
Co-authored-by: Jan Šlégl <slegl.jan@gmail.com>
Co-authored-by: Dean Galvin <dean.galvin@live.com>
Co-authored-by: ivica00 <ivica00@users.noreply.github.com>
Co-authored-by: overlordxrz-source <overlordxrz-source@users.noreply.github.com>
Co-authored-by: Yunus Shaikh <75296019+yunusshaikh7@users.noreply.github.com>
Co-authored-by: xXPBSXx <20614131+xXPBSXx@users.noreply.github.com>
Co-authored-by: LeandroLP23 <leandroplacidi@gmail.com>
Co-authored-by: thibaut <thibaut-leaux-angeli@live.fr>
Co-authored-by: Adrià Franch <adriadam10@gmail.com>
@jotitadev jotitadev mentioned this pull request Oct 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agc libSceAgc* docs shader core/shader

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants